package com.example.emos.wx.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.example.emos.wx.entity.MessageEntity;
import com.example.emos.wx.entity.TbDept;
import com.example.emos.wx.entity.TbUser;
import com.example.emos.wx.exception.EmosException;
import com.example.emos.wx.mapper.TbDeptDao;
import com.example.emos.wx.mapper.TbUserDao;
import com.example.emos.wx.service.UserService;
import com.example.emos.wx.task.MessageTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @ClasName UserServiceImpl
 * @Descripution TODO
 * @Author leikw
 * @Date 2023/2/4 16:40
 * @Version V1.0
 */
@Service
@Slf4j
@Scope("prototype")
public class UserServiceImpl implements UserService {

    @Value("${wx.app-id}")
    private String appId;

    @Value("${wx.app-secret}")
    private String appSecret;

    @Autowired
    private TbUserDao userDao;

    @Autowired
    MessageTask messageTask;

    @Autowired
    private TbDeptDao deptDao;

    /**
     * @Author leikw
     * @Description 根据前台临时登陆凭证获取openId
     * @Date  2023/2/4 16:47
     * null
     */
    private String getOpenId(String code){
        String url="https://api.weixin.qq.com/sns/jscode2session";
        HashMap map=new HashMap();
        map.put("appid", appId);
        map.put("secret", appSecret);
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");
        String response= HttpUtil.post(url,map);
        JSONObject json= JSONUtil.parseObj(response);
        String openId=json.getStr("openid");
        if(openId==null||openId.length()==0){
            throw new RuntimeException("临时登陆凭证错误");
        }
        return openId;
    }


    /**
     * @Author leikw
     * @Description 注册用户并返回id
     * [注册码, 微信临时凭证, 用户名, 照片地址]
     * @Date  2023/2/4 16:53
     * int
     */
    @Override
    public int registerUser(String registerCode, String code, String nickname, String photo) {

        //判断是否为超级管理员注册
        if(registerCode.equals("000000")){
            //判断是否存在超级管理员 （只有一个超级管理员）
            boolean bool=userDao.haveRootUser();
            //如果没有创建账号然后返回用户id
            if(!bool){
                String openId=getOpenId(code);
                HashMap param=new HashMap();
                param.put("openId", openId);
                param.put("nickname", nickname);
                param.put("photo", photo);
                param.put("role", "[0]");
                param.put("status", 1);
                param.put("createTime", new Date());
                param.put("root", true);
                userDao.insert(param);
                int id=userDao.searchIdByOpenId(openId);

                //注册成功后发送消息到用户账号
                MessageEntity entity=new MessageEntity();
                entity.setSenderId(0);
                entity.setSenderName("系统消息");
                entity.setUuid(IdUtil.simpleUUID());
                entity.setMsg("欢迎您注册成为超级管理员，请及时更新你的员工个人信息。");
                entity.setSendTime(new Date());
                messageTask.sendAsync(id+"",entity);

                return id;
            }
            else{
                throw new EmosException("无法绑定超级管理员账号");
            }
        } else{

        }
        return 0;
    }

    /**
     * @Author leikw
     * @Description 根据用户id查询用户权限
     * @Date  2023/2/4 18:51
     * null
     */
    @Override
    public Set<String> searchUserPermissions(int userId) {
        return userDao.searchUserPermissions(userId);
    }

    /**
     * @Author leikw
     * @Description 根据微信临时授权码查询用户信息
     * @Date  2023/2/4 18:51
     * null
     */
    @Override
    public int login(String code) {
        String openId=getOpenId(code);
        Integer id=userDao.searchIdByOpenId(openId);
        if(id==null){
            throw new EmosException("帐户不存在");
        }
        //登录后接收消息 数据被保存在MongoDB
        messageTask.receiveAsync(id+"");
        return id;
    }

    /**
     * @Author leikw
     * @Description 查询用户信息
     * @Date  2023/2/5 15:31
     */
    @Override
    public TbUser searchById(int userId) {
        return userDao.searchById(userId);
    }

    /**
     * @Author leikw
     * @Description // 查询用户入职日期
     * @Date  2023/2/6 15:06
     * null
     */
    @Override
    public String searchUserHiredate(int userId) {
        return userDao.searchUserHiredate(userId);
    }

    /**
     * @Author leikw
     * @Description 查询用户信息
     * @Date  2023/2/6 16:14
     * null
     */
    @Override
    public HashMap searchUserSummary(int userId) {
        return userDao.searchUserSummary(userId);
    }

    /**
     * @Author leikw
     * @Description 查询用户列表
     * @Date  2023/2/8 16:07
     */
    @Override
    public ArrayList<HashMap> searchUserGroupByDept(String keyword) {
        ArrayList<HashMap> list_1=deptDao.searchDeptMembers(keyword);
        ArrayList<HashMap> list_2=userDao.searchUserGroupByDept(keyword);
        //组装数据
        for(HashMap map_1:list_1){
            long deptId=(Long)map_1.get("id");
            ArrayList members=new ArrayList();
            for(HashMap map_2:list_2){
                long id=(Long) map_2.get("deptId");
                if(deptId==id){
                    members.add(map_2);
                }
            }
            map_1.put("members",members);
        }
        return list_1;
    }

    /**
     * @Author leikw
     * @Description 查询成员信息
     * @Date  2023/2/8 16:49
     */
    @Override
    public ArrayList<HashMap> searchMembers(List param) {
        ArrayList<HashMap> list=userDao.searchMembers(param);
        return list;
    }

    /**
     * @Author leikw
     * @Description 查询用户信息
     * @Date  2023/2/8 22:11
     * null
     */
    @Override
    public List<HashMap> selectUserPhotoAndName(List param) {
        return userDao.selectUserPhotoAndName(param);
    }


}
